﻿using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using AlipaySDK.Dto.Auth;
using AlipaySDK.Helper;
using Common.Logging;
using Newtonsoft.Json;
using OutDbContext;
using User.Api.Helpers;

namespace User.Api.Controllers
{
    public class CityController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(CityController));
        private GdsfybjyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new GdsfybjyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        [AllowAnonymous]
        [Route("WxCity/Instructions")]
        [HttpGet]
        public HttpResponseMessage Portal(string service, string auth_code, string state, string app_id, string scope, string source)
        {
            string failedUrl = ConfigurationManager.AppSettings["H5BaseAddress"] + "/index/401";

            if (string.IsNullOrEmpty(auth_code))
            {
                var res = Request.CreateResponse(HttpStatusCode.Redirect);
                res.Headers.Location = new Uri(failedUrl);
                return res;
            }

            if (state != WxOauth2State)
            {
                var res = Request.CreateResponse(HttpStatusCode.Redirect);
                res.Headers.Location = new Uri(failedUrl);
                return res;
            }

            GetOauth2OpenIdResponse result = null;

            //通过，用code换取access_token
            try
            {
                result = Auth.GetOauth2OpenId(auth_code, app_id);
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("服务窗网页授权获取用户信息第一步出错，授权码:{0},信息：{1}", auth_code, JsonConvert.SerializeObject(ex));

                var res = Request.CreateResponse(HttpStatusCode.Redirect);
                res.Headers.Location = new Uri(failedUrl);
                return res;
            }
            if (result.ResultCode != "0")
            {
                var res = Request.CreateResponse(HttpStatusCode.Redirect);
                res.Headers.Location = new Uri(failedUrl);
                return res;
            }

            GetOauth2UserInfoResponse userInfo = null;
            try
            {
                userInfo = Auth.GetOauth2UserinfoShare(app_id, result.AccessToken);
                // TODO 获取用户信息

            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("服务窗网页授权获取用户信息第二步出错，信息：{0}", JsonConvert.SerializeObject(ex));
            }

            long userId = 0;
            var openId = result.OpenId;

            using (var ctx = new GdsfybjyWeiXinEntities())
            {
                var user = ctx.WxUsers.FirstOrDefault(x => x.OpenId == openId);
                if (user != null)
                {
                    user.RecStatus = 1;
                    user.LastActiveDt = DateTime.Now;
                    user.UnsubscribeDt = null;
                    user.RecUpdateDt = DateTime.Now;
                    user.UserRealName = userInfo?.RealName;
                    user.CertNo = userInfo?.CertNo;
                    user.Mobile = userInfo?.Mobile;
                    user.Gender = userInfo?.Gender;
                }
                else
                {
                    user = new OutDbContext.WxUser
                    {
                        OpenId = openId,
                        SubscribeDt = DateTime.Now,
                        LastActiveDt = DateTime.Now,
                        IsBkMember = 0,
                        RecStatus = 1,
                        RecCreateDt = DateTime.Now,
                        UserType = "AliPay",
                        UserRealName = userInfo?.RealName,
                        CertNo = userInfo?.CertNo,
                        Mobile = userInfo?.Mobile,
                        Gender = userInfo?.Gender
                    };

                    ctx.WxUsers.Add(user);
                }

                ctx.SaveChanges();
                userId = user.Id;
            }

            var h5BaseAddress = ConfigurationManager.AppSettings["H5BaseAddress"];
            var url = "";

            switch (service)
            {

                case "service_dangtianguahao"://当天挂号&取号&预约挂号&候诊队列
                    url = h5BaseAddress + "/index/city-portal?type=service_dangtianguahao";
                    break;
                case "service_jiuzhenjiaofei"://就诊缴费
                    url = h5BaseAddress + "/index/get-bill";
                    break;
                case "service_qubaogaodan"://取检查.检验报告单
                    url = h5BaseAddress + "/index/city-portal?type=service_qubaogaodan";
                    break;
                case "my_danju"://挂号单，缴费单
                    url = h5BaseAddress + "/index/city-portal?type=my_danju";
                    break;
                case "my_juzhenka"://我的就诊卡
                    url = h5BaseAddress + "/index/manage-card";
                    break;
            }

            var response = Request.CreateResponse(HttpStatusCode.Redirect);
            response.Headers.Location = new Uri(url);

            var cookie = new CookieHeaderValue("AzuCookie",
                LocalUserTokenHelper.GenerateLocalToken(userId, openId));
            //cookie.Domain = Request.RequestUri.Host;
            cookie.Path = "/";

            var cityCookie = new CookieHeaderValue("IsCity", "1");
            //cookie.Domain = Request.RequestUri.Host;
            cityCookie.Path = "/";

            response.Headers.AddCookies(new[] { cookie, cityCookie });

            return response;
        }

        [HttpGet]
        [ActionName("GetTemplateMsg")]
        public string GetTemplateMsg(int orderId, string msgtype)
        {
            var tempLateParam = "";

            switch (msgtype)
            {
                case "guahao":
                    tempLateParam = GetGuohaoTempLateParam(orderId);
                    break;
                case "jiaofei":
                    tempLateParam = GetJiaofeiTempLateParam(orderId);
                    break;
                case "guahaotuifei":
                    tempLateParam = GetGuohaoTuifeiTempLateParam(orderId);
                    break;
            }

            string tempLateParamUrlEncode = System.Web.HttpUtility.UrlEncode(tempLateParam);
            string cityurl = "https://city.weixin.qq.com/cgi-bin/entry?result_data=" + tempLateParamUrlEncode + "#wechat_redirect";

            return cityurl;
        }

        const string TopColor = "#0000FF";

        const string FirstColor = "#173177";

        const string RemarkColor = "#173177";

        const string NoticeColor = "#173177";

        private string GetGuohaoTempLateParam(int orderId)
        {
            string tempLateParam = "";
            using (var ctx = new GdsfybjyWeiXinEntities())
            {
                var apptorder = ctx.ApptOrders.First(x => x.Id == orderId);
                var wxUserId = apptorder?.WxUserId ?? 0;
                var user = ctx.WxUsers.FirstOrDefault(x => x.Id == wxUserId);
                string patientname = apptorder?.CardName ?? "";

                var url = GetH5Url("/index/reg-order-detail/" + orderId);

                string strfirst = string.Format("您已{0}成功\r姓名：{1} 卡号：{2} 挂号费用：{3}\r就诊日期：{4} 就诊时间：{5} ", apptorder.OrderType == "0" ? "预约" : "挂号", patientname, apptorder.CardNo, apptorder.SumFee, apptorder.RegDate, apptorder.OrderType == "2" ? apptorder.StartTime + "-" + apptorder.EndTime : apptorder.StartTime);
                string strRemark = "";
                if (apptorder.DeptName == "儿科门诊(番禺)" || apptorder.DeptName == "儿童保健科门诊(番禺)" || apptorder.DeptName == "产科门诊(番禺)" || apptorder.DeptName == "产前诊断门诊(番禺)")
                {
                    strRemark = "温馨提示：请提前15分钟到护士站报到确认！因故迟到、未超过预约就诊时间30分钟者，报到确认后，按系统排在当前三位候诊患者之后就诊；迟到超过30分钟以上、未超过正常下班时间者，系统安排在本班次最后就诊或者退号后重新挂号排队就诊。请见门诊就诊秩序。";
                }
                var temp = new
                {
                    touser = user.OpenId ?? "",
                    template_id = "Lbfgmg9Ws4_XLIRnHPXyGc3xpiQObU3AGXPbyehWM3w",
                    url = url,
                    topcolor = TopColor,
                    data = new
                    {
                        first = new
                        {
                            value = strfirst,
                            color = FirstColor
                        },
                        keyword1 = new
                        {
                            value = apptorder.OrderNo,
                            color = NoticeColor
                        },
                        keyword2 = new
                        {
                            value = "广东省妇幼保健院",
                            color = NoticeColor
                        },
                        keyword3 = new
                        {
                            value = apptorder.DeptName,
                            color = NoticeColor
                        },
                        keyword4 = new
                        {
                            value = apptorder.DoctorName,
                            color = NoticeColor
                        },
                        keyword5 = new
                        {
                            value = apptorder.VisitNo,
                            color = NoticeColor
                        },
                        remark = new
                        {
                            value = strRemark,
                            color = RemarkColor
                        }
                    }
                };
                tempLateParam = JsonConvert.SerializeObject(temp);
            }
            return tempLateParam;
        }

        private string GetJiaofeiTempLateParam(int orderId)
        {
            string tempLateParam = "";
            using (var ctx = new GdsfybjyWeiXinEntities())
            {
                var billorder = ctx.BillOrders.First(x => x.Id == orderId);
                var wxUserId = billorder?.WxUserId ?? 0;
                var user = ctx.WxUsers.FirstOrDefault(x => x.Id == wxUserId);
                string patientname = billorder?.CardName ?? "";

                var url = GetH5Url("/index/bill-order-detail/" + orderId);

                string strfirst = string.Format("您已缴费成功\r开单时间：{0} 开单科室：{1} ", billorder.OrderDate, billorder.OrderDept);

                string strmoney = billorder.PrescMoney.ToString();
                if (billorder.YiBaoStatus != null && billorder.YiBaoStatus == 1)
                {
                    strmoney = strmoney + "(医保：" + billorder.YibaoMoney.ToString() + "个人：" + billorder.PersonalMoney.ToString() + ")";
                }
                string strRemark = "如需补打发票，请于当天移步人工窗口办理，过期无效。";

                var temp = new
                {
                    touser = user?.OpenId ?? "",
                    template_id = "PMMm6R1w5VKVXssmd5c7b3JYCgwCXGtl3TogNNY-UUU",
                    url = url,
                    topcolor = TopColor,
                    data = new
                    {
                        first = new
                        {
                            value = strfirst,
                            color = FirstColor
                        },
                        keyword1 = new
                        {
                            value = "就诊（" + billorder.ClinicNo + ")",
                            color = NoticeColor
                        },
                        keyword2 = new
                        {
                            value = strmoney,
                            color = NoticeColor
                        },
                        keyword3 = new
                        {
                            value = patientname + "(" + billorder.CardNo + ")",
                            color = NoticeColor
                        },

                        remark = new
                        {
                            value = strRemark,
                            color = RemarkColor
                        }
                    }
                };
                tempLateParam = JsonConvert.SerializeObject(temp);
            }
            return tempLateParam;
        }

        private string GetGuohaoTuifeiTempLateParam(int orderId)
        {
            string tempLateParam = "";
            using (var ctx = new GdsfybjyWeiXinEntities())
            {
                var apptorder = ctx.ApptOrders.First(x => x.Id == orderId);
                var wxUserId = apptorder?.WxUserId ?? 0;
                var user = ctx.WxUsers.FirstOrDefault(x => x.Id == wxUserId);

                string patientname = apptorder?.CardName ??"";

                var url = GetH5Url("/index/portal");

                string strfirst = string.Format("您已取消预约成功\r姓名：{0}\r卡号：{1}\r科室：{2}\r医生：{3}\r挂号费用：{4}\r就诊日期：{5}\r就诊时间：{6} ", patientname, apptorder.CardNo, apptorder.DeptName, apptorder.DoctorName, apptorder.SumFee, apptorder.RegDate, apptorder.OrderType == "2" ? apptorder.StartTime + "-" + apptorder.EndTime : apptorder.StartTime);

                string strRemark = " ";

                var temp = new
                {
                    touser = user?.OpenId,
                    template_id = "eAXUiutYpm5ZccaERhmE451HsGXjcsR-davaoYF8_hE",
                    url = url,
                    topcolor = TopColor,
                    data = new
                    {
                        first = new
                        {
                            value = strfirst,
                            color = FirstColor
                        },
                        keyword1 = new
                        {
                            value = apptorder.OrderNo,
                            color = NoticeColor
                        },
                        keyword2 = new
                        {
                            value = apptorder.SumFee.ToString(),
                            color = NoticeColor
                        },
                        keyword3 = new
                        {
                            value = apptorder.RefundTime.ToString(),
                            color = NoticeColor
                        },
                        keyword4 = new
                        {
                            value = "2-5个工作日，具体到账时间以银行通知为准",
                            color = NoticeColor
                        },
                        remark = new
                        {
                            value = strRemark,
                            color = RemarkColor
                        }
                    }
                };
                tempLateParam = JsonConvert.SerializeObject(temp);
            }
            return tempLateParam;
        }

        private static readonly string WxOauth2State = "GbkYin666";

        /// <summary>
        /// 获取网页地址
        /// </summary>
        /// <param name="routePath"></param>
        /// <returns></returns>
        public string GetH5Url(string routePath)
        {

            var h5BaseAddress = ConfigurationManager.AppSettings["H5BaseAddress"];
            var baseAddress = ConfigurationManager.AppSettings["BaseAddress"];
            var appId = ConfigurationManager.AppSettings["WeixinAppId"];

            var url = h5BaseAddress + routePath;
            var redirectUrl = baseAddress + "api/Auth/WxOauth2?url=" + HttpUtility.UrlEncode(url);
            //https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2015052700092241&auth_skip=false&scope=auth_userinfo&state={WxOauth2State}&redirect_uri=http://wx.e3861.com/api/Auth/WxOauth2?url=http://wx.e3861.com/h5/index.html#!/index/get-queue
            var oauth2Url =
                $"https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id={appId}&auth_skip=false&scope=auth_userinfo&state={WxOauth2State}&redirect_uri={HttpUtility.UrlEncode(redirectUrl)}";

            return oauth2Url;
        }
    }
}
